package com.lemon.components.ant.docmaker;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.lemon.components.ant.project.beans.ColumnInfo;
import com.lemon.components.ant.project.beans.TableInfo;
import com.lemon.components.ant.util.ConfigUtil;
import com.lemon.components.docs.mysql.MysqlLocalTool;
import com.lemon.ui.codemaker.component.RecentlyFile;

public class MysqlDoc {

	public void exportTables(String savePath) throws Exception {
		File excelFile = new File(savePath);
		if(!excelFile.exists()) {
			excelFile = new File(savePath+".xlsx");
		}
		var tables = MysqlLocalTool.getTableInfo(ConfigUtil.getInstance(RecentlyFile.configFilePath).getProjectInfoNoTable());
		try (XSSFWorkbook workbook = new XSSFWorkbook()) {
			XSSFCellStyle headStyle = workbook.createCellStyle();
			//设置前景颜色
			headStyle.setFillForegroundColor(IndexedColors.LIME.getIndex());
			headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
			
			
			XSSFCellStyle contentStyle = workbook.createCellStyle();
			contentStyle.setWrapText(true);
			contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
			
			for(TableInfo item1:tables) {
				XSSFSheet sheet = workbook.createSheet(item1.getTableComment()+"("+item1.getTableName()+")");
				sheet.setColumnWidth(0, 20*256);
				sheet.setColumnWidth(1, 20*256);
				sheet.setColumnWidth(2, 20*256);
				XSSFRow row = sheet.createRow(0);
				String[] title = new String[]{"备注", "编码", "类型"};
				// 第一行标题
	            for (int i = 0; i < title.length; i++) {
	                XSSFCell cellTitle = row.createCell(i, CellType.STRING);
	                cellTitle.setCellValue(title[i]);
	                cellTitle.setCellStyle(headStyle);
	            }
	            for (int i = 1; i < item1.getColumns().size(); i++) {
	            	ColumnInfo column = item1.getColumns().get(i-1);
	            	XSSFRow dataRow = sheet.createRow(i);
	            	XSSFCell cell1 = dataRow.createCell(0, CellType.STRING);
	            	cell1.setCellValue(column.getColumnRemark());
	            	cell1.setCellStyle(contentStyle);
	            	
	            	XSSFCell cell2 = dataRow.createCell(1, CellType.STRING);
	            	cell2.setCellValue(column.getColumnCode());
	            	cell2.setCellStyle(contentStyle);
	            	
	            	XSSFCell cell3 = dataRow.createCell(2, CellType.STRING);
	            	cell3.setCellValue(column.getColumnType());
	            }
			}
			workbook.write(new FileOutputStream(excelFile));
			workbook.close();
		} catch (Exception e) {
			throw e;
		}
	}
	
}